<template>
	<view class="score-mall-wrap" :style="{ margin }">
		<view class="title-wrap">
			<view class="left">福分商城</view>
			<view class="right" @tap="toUrl('/pageScore/scoreMall/index')">
				<text>查看全部</text>
				<image src="@/static/new/arrow-right.png"></image>
			</view>
		</view>
		
		<view class="list">
			<view class="item" v-for="item in scoreMallList">
				<view class="price-num">
					<view class="price">
						<text>￥<text>{{ item.price ? item.price / 100 : 0 }}</text></text>
						<view>满{{item.payAmount ? item.payAmount / 100 : '--'}}元可用</view>
					</view>
					<!-- <view v-if="item.awardType == 0" class="price">
						<text>￥<text>{{ item.price }}</text></text>
					</view>
					<view v-if="item.awardType == 1" class="goods">
						<image :src="item.imgUrl"></image>
					</view> -->
					<!-- <image :src="item.imgUrl"></image> -->
					<view class="num">
						剩余：{{ item.syNum }}
					</view>
					<view class="exchanged">
						已兑：{{ item.getNum }}
					</view>
				</view>
				
				<view class="name">{{ item.name }}</view>
				<!-- <view v-if="false" class="desc">满100.01元减100元</view> -->
				<!-- <view v-else-if="item.awardType == 1" class="desc">{{ '价值：'+item.price +'元'}}</view> -->
				<!-- <view class="desc">价值：{{ item.price ? item.price / 100 : 0 }}元</view> -->
				<view class="need-btn">
					<text class="need">消耗{{ item.scoreNeed }}福分</text>
					<text class="btn" :style="{ filter: !isLogin ? 'grayscale(1)' : 'initial' }" @click="scoreExchange(item)">兑换</text>
				</view>
			</view>
		</view>
		<!-- 通用二次弹窗组件 -->
		<gzConfirm ref="gzConfirmRef" />
		<gzListNull :list="scoreMallList"></gzListNull>
	</view>
</template>

<script setup>
	import { onLoad } from '@dcloudio/uni-app'
	import { defineProps, reactive, ref, getCurrentInstance } from 'vue'
	import { $scoreMallList, $scoreExchange, $checkUserPayAuth } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import appConfig from '@/config/appConfig.js';
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
	
	const props = defineProps({
		margin:{
			type: String,
			default: '0 24rpx'
		},
		// 用户福分总量
		socreTotalNum: {
			type: [String,Number],
			default: 0
		},
		// 兑换回调
		exchangeCallback: {
			type: Function,
			require: true,
			default: () => {}
		},
		// 福分商城数据
		scoreMallList: {
			type: Array,
			default: []
		},
		// 用户是否登录
		isLogin: {
			type: Boolean,
			default: false
		},
		// isToastShow 历史福分是否在同步中
		isToastShow: {
			type: Boolean
		}
	})
	// 组件对象
	const gzConfirmRef = ref()
	const userId = storageManage.userId()
	const fansId = storageManage.fansId()
	// 数据源
	const vdata = reactive({
	})
	
	onLoad(async ({ item }) => {
		// 自动兑换
		if(item){
			item = JSON.parse(decodeURIComponent(item))
			uni.showLoading({ title: '兑换中...', mask: true })
			exchangeHandler(item)
		}
	})
	
	// 用户id
	/**
	 * 路由跳转
	 */
	function toUrl(url){
		getApp().preventActive(()=>{
			if(!props.isLogin) return
			if(props.isToastShow) return	// 历史福分正在同步中 不允许操作兑换
			uni.navigateTo({
				url
			})
		})
	}
	/**
	 * 兑换提示 奖品兑换
	 */
	function scoreExchange(item){
		getApp().preventActive(()=>{
			if(!props.isLogin) return
			if(props.isToastShow) return	// 历史福分正在同步中 不允许操作兑换
			if(item.syNum == 0){
				$infoBox.toast('商品已兑完！')
				return
			}
			uni.showModal({
				title: '兑换提示',
				content: `请确定是否消耗${item.scoreNeed}福分兑换该奖品`,
				async success({ cancel }) {
					if(cancel) return
					// 校验余量
					if(item.scoreNeed - 0 > props.socreTotalNum - 0){
						$infoBox.toast('剩余福分不足！')
						return
					}
					uni.showLoading({ title: '兑换中...', mask: true })
					// 校验出资方
					if(item.ifCode){	// 当前卡券为三方出资
						// 判断本地是否缓存支付授权
						if(!storageManage.openId(`${item.ifCode}-openId`)){	// 本地不存在支付授权 请求授权参数进行授权
							const { bizData:payAuthBizData } = await $checkUserPayAuth({ scoreExchangeId: item.scoreExchangeId })
							const { flag, url, ifCode, openId:fansPayOpenId } = payAuthBizData
							if(url && ifCode){	// 说明用户未授权
								uni.hideLoading()
								// 跳转授权页面
								appConfig.url = url
								getApp().globalData.temp_path = `/pages/pageBlessingPoints/pageBlessingPoints?type=tabbar&item=${encodeURIComponent(JSON.stringify(item))}`
								getApp().globalData.temp_ifcode = ifCode
								uni.reLaunch({
									url: '/pages/openid/openid'
								})
								return
							}
							// 用户已授权时 接口只会返回 flag和openId
							// 说明用户已授权 但是用户端未缓存 更新用户缓存 防止每次请求都要校验用户授权
							storageManage.openId(`${item.ifCode}-openId`,fansPayOpenId)
						}
					}
					// 发起兑换
					exchangeHandler(item)
				}
			})
		})
	}
	
	// 发起兑换处理 item 兑换对象 信息
	async function exchangeHandler(item){
		// 已授权且用户福分余量充足 允许兑换奖品
		const { code, bizData } = await $scoreExchange({ infoType: item.awardType - 0, scoreExchangeId: item.scoreExchangeId, name: item.name })
		if(code === 40006){	// 5分钟内进行过一次兑换
			uni.hideLoading()
			uni.showModal({
				title: '提示',
				content: bizData || '您已兑换成功，是否需要再次兑换？',
				async success({ cancel }) {
					if (cancel) return
					// 用户确认兑换
					uni.showLoading({ title: '兑换中...', mask: true })
					await $scoreExchange({ infoType: item.awardType - 0, scoreExchangeId: item.scoreExchangeId, name: item.name, state: 1 })
					$infoBox.toast('兑换成功！')
					// 回调刷新福分商城数据 以及更新福分数量
					props.exchangeCallback()
				}
			})
		}else{
			$infoBox.toast('兑换成功！')
			// 回调刷新福分商城数据 以及更新福分数量
			props.exchangeCallback()
		}
	}
</script>

<style lang="less">
	.score-mall-wrap{
		margin: 0 24rpx;
		padding: 44rpx 32rpx;
		background: #fff;
		border-radius: 24rpx;
		
		.title-wrap{
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.left{
				font-weight: bold;
				font-size: 34rpx;
			}
			.right{
				text{
					font-weight: 400;
					font-size: 28rpx;
					color: #999999;
				}
				image{
					width: 16rpx;
					height: 20rpx;
					margin-left: 12rpx;
				}
			}
		}
		
		.list{
			display: grid;
			grid-template-columns: repeat(3, 1fr);
			grid-column-gap: 10px;
			.item{
				margin-top: 40rpx;
				text-align: center;
				overflow: hidden;
				.price-num{
					position: relative;
					.exchanged{
						position: absolute;
						top: 0;
						right: 0;
						background: rgba(0, 0, 0, 0.5);
						font-weight: 400;
						font-size: 24rpx;
						color: #FFFFFF;
						padding: 6rpx;
						border-radius: 0 15rpx 0 15rpx;
					}
					image{
						width: 202rpx;
						height: 152rpx;
						border-radius: 15rpx 15rpx 0 0;
					}
					.price{
						width: 100%;
						height: 152rpx;
						color: #FFF;
						font-weight: bold;
						display: flex;
						justify-content: center;
						align-items: center;
						background-image: url('@/static/new/blessingPoints/award-bg.png');
						background-size: 100%;
						background-position: 0 0;
						background-repeat: no-repeat;
						position: relative;
						text{
							font-size: 32rpx;
							text{
								font-size: 64rpx;
							}
						}
						view{
							font-size: 24rpx;
							font-weight: normal;
							position: absolute;
							bottom: 0;
						}
					}
					.num{
						background: #E9F9F3;
						font-size: 24rpx;
						color: #24C789;
						border-radius: 0 0 15rpx 15rpx;
						padding: 10rpx 0;
						display: flex;
						align-items: center;
						justify-content: center;
					}
				}
				
				.name{
					margin: 16rpx 0 8rpx;
					color: #333333;
					font-weight: bold;
					font-size: 26rpx;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
				.desc{
					margin-bottom: 16rpx;
					font-size: 24rpx;
					color: #999999;
				}
				.need-btn{
					background: #FBF0E8;
					border-radius: 25rpx;
					display: flex;
					align-items: center;
					position: relative;
					height: 40rpx;
					.need{
						font-size: 20rpx;
						color: #FF8833;
						padding-left: 14rpx;
					}
					.btn{
						display: block;
						font-size: 20rpx;
						width: 70rpx;
						height: 40rpx;
						color: #FFFFFF;
						background-image: url('@/static/new/blessingPoints/icon-exchange.png');
						background-size: 100% 100%;
						background-position: 0 0;
						background-repeat: no-repeat;
						line-height: 40rpx;
						// text-align: center;
						box-sizing: border-box;
						padding-left: 20rpx;
						padding-right: 10rpx;
						position: absolute;
						right: 0;
					}
				}
			}
		}
	}
</style>